'use client'
import React, { useRef, useEffect, createContext } from 'react'
import AutoResizeTextarea, {
  type TextareaHandles,
} from '@/components/AutoResizeTextarea/AutoResizeTextarea'
import store from '@/store'
// 辅助函数：滚动聊天区域到底部
export const EventContext = createContext<() => void>(() => {})

export default function FooterInput({
  setAutoScroll,
  setIsSend,
}: {
  setAutoScroll: (autoScroll: boolean) => void
  setIsSend: (autoScroll: boolean) => void
}) {
  const receive = store.Chat((state) => state.receive)
  const texTareaRef = useRef<TextareaHandles>(null)
  // 发送消息，建立一个单独的 SSE 连接用于当前消息的回复
  const sendMsg = async () => {
    // 清空文本域并获取输入的消息
    texTareaRef?.current?.clearValue()
    const message: string = texTareaRef.current?.getValue() || ''
    if (!message) return
    setAutoScroll(true)
    setIsSend(true)
    try {
      const temporary = Date.now() + Math.random()
      // 先将用户消息加入到聊天记录中
      receive({
        id: null,
        user_id: '1',
        sender_type: 'user',
        message,
        temporary,
      })

      // 这里使用 EventSource 的方式发送消息并接收回复
      const msgEncoded = encodeURIComponent(message)
      const resEventSource = new EventSource(
        `/apis/chat/send?message=${msgEncoded}`
      )

      resEventSource.onmessage = (event) => {
        try {
          setIsSend(false)
          const data = JSON.parse(event.data)
          if (data.error) {
            console.error('发送消息失败:', data.error)
            return
          }
          if (data) {
            let timer = setTimeout(() => {
              clearTimeout(timer)
              receive({ data, sender_type: 'chat', temporary })
            }, 200)
          }
        } catch (err) {
          console.error('解析 SSE 消息出错', err)
        }
      }

      resEventSource.onerror = (error) => {
        console.error('单独消息 SSE 连接失败:', error)
        resEventSource.close()
        setIsSend(false)
      }
    } catch (error) {
      setIsSend(false)
      console.error('发送消息时出错:', error)
    }
  }

  return (
    <EventContext.Provider value={sendMsg}>
      <div className="min-h-20 bg-gre border-t-2 p-3 pb-5 relative">
        <div className="w-full border flex rounded-2xl p-1 pl-3 pt-3">
          <AutoResizeTextarea
            nodeProps={{ placeholder: 'Enter 发送，Shift+Enter换行' }}
            ref={texTareaRef}
          ></AutoResizeTextarea>
          <button
            onClick={sendMsg}
            className="bg-primary text-white h-10 m-3 p-3 rounded-md text-xs flex items-center absolute right-2 bottom-5"
          >
            <svg
              className="w-4 h-4 mr-1"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="4447"
              width="200"
              height="200"
            >
              <path
                d="M899.925333 172.080762a48.761905 48.761905 0 0 1 0 28.525714l-207.969523 679.448381a48.761905 48.761905 0 0 1-81.115429 20.187429l-150.552381-150.552381-96.304762 96.329143a24.380952 24.380952 0 0 1-41.593905-17.237334v-214.966857l275.821715-243.370667-355.57181 161.596953-103.253333-103.228953a48.761905 48.761905 0 0 1 20.23619-81.091047L838.997333 139.702857a48.761905 48.761905 0 0 1 60.903619 32.353524z"
                p-id="4448"
                fill="#ffffff"
              ></path>
            </svg>
            发送
          </button>
        </div>
      </div>
    </EventContext.Provider>
  )
}
